import datetime
import json
import talib

import numpy as np
import os

import baostock as bs
import pandas as pd

# Create your views here.
from django.core.paginator import Paginator
from django.db.models import Count
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from yaml import serialize

from chartstest.datasViews import connectushare
from chartstest.models import TusharDate, DealDetail, stock_basic, cctv_news, coinInfo
import tushare as ts

from stock.models import index_daily, indexBasic
from utils.MyEncoder import MyEncoder


# 首页
def indexbasic(request):
    data_list = []
    # query = TusharDate.objects.all().query
    # query.group_by = ['tscode']
    # book_list = QuerySet(query=query, model=TusharDate)
    # tscode 分组
    # result = coinInfo.objects.values('id').annotate(Count=Count('tscode')).order_by('-id')[:3]
    result = coinInfo.objects.all()
    print(type(result))
    # print(result.count())

    for obj in result:
        # print(obj)
        data_list.append(obj)

    # for i in range(0, len(book_list)):
    #     #data_list.append(book_list[i][9])
    #     print(i)
    # print(book_list.count())

    # print("json:" + json.dumps(data_list))
    # print(data_list)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'stock/indexbasic.html')


def stockIndex(request):
    data_list = []
    # query = TusharDate.objects.all().query
    # query.group_by = ['tscode']
    # book_list = QuerySet(query=query, model=TusharDate)
    # tscode 分组
    # result = coinInfo.objects.values('id').annotate(Count=Count('tscode')).order_by('-id')[:3]
    result = coinInfo.objects.all()
    print(type(result))
    # print(result.count())

    for obj in result:
        # print(obj)
        data_list.append(obj)

    # for i in range(0, len(book_list)):
    #     #data_list.append(book_list[i][9])
    #     print(i)
    # print(book_list.count())

    # print("json:" + json.dumps(data_list))
    # print(data_list)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'stock/index.html')


# 在处理函数加此装饰器即可
# 指数日线数据下载
@csrf_exempt
def downDate(request):
    tscode = request.POST['tscode']
    start = request.POST['startTime']
    end = request.POST['endTime']

    if start == '' or end == "":
        return

    startTime = start.replace('-', '')
    endTime = end.replace('-', '')
    # 从tushare查询某只股票日线数据
    # pro = connectushare
    # 查询当前所有正常上市交易的股票列表
    pro = ts.pro_api('09c23ca7df4d6e0692459fd98de6207c1d687158fb1e946f5be77af8')

    pd.set_option('display.max_columns', None)

    begin = datetime.date(2017, 1, 21)
    end = datetime.date(2019, 4, 7)
    datas = pro.index_daily(ts_code=tscode, start_date=startTime, end_date=endTime)
    # 将date值转换为datetime类型，并且设置成index
    # dataform 转成list
    train_data = np.array(datas)  # np.ndarray()
    train_x_list = train_data.tolist()  # list
    # print(train_x_list)
    # 数据排序，正序
    train_x_list.sort(key=lambda x: x[0], reverse=True)

    for i in range(1, len(train_x_list)):
        tt = train_x_list[i]
        print(tt)
        print("时间:" + tt[0])
        print("标题:" + tt[1])
        c = index_daily()
        c.ts_code = tt[0]
        c.trade_date = tt[1]
        c.close = tt[2]

        c.open = tt[3]

        c.high = tt[3]

        c.low = tt[5]

        c.pre_close = tt[6]
        c.change = tt[7]
        c.pct_chg = tt[8]

        c.vol = tt[9]
        c.amount = tt[10]
        # 去重
        n = index_daily.objects.filter(ts_code=tt[0], trade_date=tt[1]).count()
        if n == 0:
            c.save()

    digital_list = {'code': 0, 'msg': 'success', 'data': ""}
    return JsonResponse(digital_list)


# 用户数据
@csrf_protect
@xframe_options_exempt
def digital_date(request):
    page = request.GET.get('page')  # 页面
    limit = request.GET.get('limit')  # 条数
    tscode = request.GET.get('tscode')  # 代码
    print(page)
    print(limit)
    digital_list = {}
    r = coinInfo.objects.filter(ts_code=tscode).all()
    datas = list(r)
    page_inator = Paginator(datas, limit)  # 分页
    contacts = page_inator.page(page)  # 请求第几页数据
    res = []  # 最终返回的结果集合
    for p in contacts:
        dic = {}
        dic['id'] = p.id
        dic['coin'] = p.coin
        dic['en_name'] = p.en_name
        dic['cn_name'] = p.cn_name
        dic['issue_date'] = p.issue_date
        dic['issue_price'] = p.issue_price
        dic['amount'] = p.amount
        dic['supply'] = p.supply
        dic['algo'] = p.algo
        dic['area'] = p.area
        dic['labels'] = p.labels
        dic['desc'] = p.desc
        res.append(dic)

    print(res)
    digital_list['code'] = 0
    digital_list['msg'] = 'success'
    digital_list['data'] = res
    digital_list['count'] = coinInfo.objects.all().count()
    return JsonResponse(digital_list)


# 在处理函数加此装饰器即可
@csrf_exempt
def downIndexBasic(request):
    # 从tushare查询某只股票日线数据
    # pro = connectushare
    # 查询当前所有正常上市交易的股票列表
    pro = ts.pro_api('09c23ca7df4d6e0692459fd98de6207c1d687158fb1e946f5be77af8')

    pd.set_option('display.max_columns', None)

    datas = pro.index_basic()
    # 将date值转换为datetime类型，并且设置成index
    # datas.index = datas.date
    # dataform 转成list
    train_data = np.array(datas)  # np.ndarray()
    train_x_list = train_data.tolist()  # list
    print(train_x_list)
    # 数据排序，正序
    train_x_list.sort(key=lambda x: x[0], reverse=True)

    for i in range(1, len(train_x_list)):
        tt = train_x_list[i]
        print(tt)
        print("时间:" + tt[0])
        print("标题:" + tt[1])
        c = indexBasic()
        c.ts_code = tt[0]
        c.name = tt[1]
        c.fullname = tt[2]

        c.market = tt[3]

        c.publisher = tt[3]

        c.index_type = tt[5]

        c.category = tt[6]
        c.base_date = tt[7]
        '''
        c.base_point = tt[8]

        c.list_date = tt[9]
        c.weight_rule = tt[10]
        c.desc = tt[11]
        c.exp_date = tt[12]
        '''
        # 去重
        n = indexBasic.objects.filter(name=tt[1]).count()
        if n == 0:
            c.save()

    digital_list = {'code': 0, 'msg': 'success', 'data': ""}
    return JsonResponse(digital_list)


# 指数日线数据
@csrf_protect
@xframe_options_exempt
def index_daily_date(request):
    page = request.GET.get('page')  # 页面
    limit = request.GET.get('limit')  # 条数
    print(page)
    print(limit)
    digital_list = {}
    r = index_daily.objects.all()
    datas = list(r)
    page_inator = Paginator(datas, limit)  # 分页
    contacts = page_inator.page(page)  # 请求第几页数据
    res = []  # 最终返回的结果集合
    for p in contacts:
        dic = {'id': p.id, 'ts_code': p.ts_code, 'trade_date': p.trade_date, 'close': p.close, 'open': p.open,
               'high': p.high, 'low': p.low, 'pre_close': p.pre_close, 'change': p.change, 'pct_chg': p.pct_chg,
               'vol': p.vol, 'amount': p.amount}
        res.append(dic)

    print(res)
    digital_list['code'] = 0
    digital_list['msg'] = 'success'
    digital_list['data'] = res
    digital_list['count'] = index_daily.objects.all().count()
    return JsonResponse(digital_list)


# 用户数据
@csrf_protect
@xframe_options_exempt
def indexbasic_date(request):
    page = request.GET.get('page')  # 页面
    limit = request.GET.get('limit')  # 条数
    tscode = request.GET.get('tscode')  # 代码
    name = request.GET.get('name')  # 简称

    print(page)
    print(limit)

    digital_list = {}

    '''
      kwargs = {}
        if A is not None:
            kwargs['name__startWith'] = A
        if B is not None:
            kwargs['address__contains'] = B
        if C is not None:
            kwargs['mobile__endWith'] = C
        ...
        ...
        personList = Person.objects.filter(**kwargs)
    
    '''
    kwargs = {}
    if tscode is not None and tscode != "":
        kwargs['ts_code__contains'] = tscode
    if name is not None and name != "":
        kwargs['name__contains'] = name

    r = indexBasic.objects.filter(**kwargs)
    datas = list(r)
    page_inator = Paginator(datas, limit)  # 分页
    contacts = page_inator.page(page)  # 请求第几页数据
    res = []  # 最终返回的结果集合
    for p in contacts:
        dic = {}
        dic['id'] = p.id
        dic['ts_code'] = p.ts_code
        dic['name'] = p.name
        dic['fullname'] = p.fullname
        dic['market'] = p.market
        dic['publisher'] = p.publisher
        dic['index_type'] = p.index_type
        dic['category'] = p.category
        dic['base_date'] = p.base_date
        dic['base_point'] = p.base_point

        res.append(dic)

    print(res)
    digital_list['code'] = 0
    digital_list['msg'] = 'success'
    digital_list['data'] = res
    digital_list['count'] = indexBasic.objects.filter(**kwargs).count()
    return JsonResponse(digital_list)


# 首页
def indexdetail(request):
    id = request.GET.get('id')  # 页面
    data_list = []
    # query = TusharDate.objects.all().query
    # query.group_by = ['tscode']
    # book_list = QuerySet(query=query, model=TusharDate)
    # tscode 分组
    # result = coinInfo.objects.values('id').annotate(Count=Count('tscode')).order_by('-id')[:3
    print(id)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'stock/indexDetails.html')
